﻿//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     彩票主流业务类库
//     银付通H5支付业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------

using CL.Enum.Common;
using CL.Game.Entity;
using CL.Json.Entity.WebAPI;
using CL.Tools.Common;
using System;

namespace CL.Game.BLL.PayInterface
{
    /// <summary>
    /// YFBH5Pay 业务
    /// </summary>
    public class YFBH5Pay
    {
        private Log log = new Log("YFBH5Pay");
        YFBH5PayHelper ybgHelper;
        public YFBH5Pay()
        {
            ybgHelper = new YFBH5PayHelper();
        }
        /// <summary>
        /// 提交支付信息
        /// </summary>
        /// <param name="userid">用户标识</param>
        /// <param name="amount">金额</param>
        /// <param name="IpAddress">本机IP</param>
        /// <param name="tbbody">商品描述</param>
        /// <param name="tbattach">附加信息</param>
        /// <returns>UserResult</returns>
        public PreparePaymentResult PostPayInfo(long userid, long amount, string IpAddress, string tbbody, string tbattach)
        {
            PreparePaymentResult result = null;
            try
            {
                if (!IsIP(IpAddress))
                    IpAddress = "127.0.0.1";

                string tbout_trade_no = GetNotbout_trade_no();
                
                //提交订单
                var postData = ybgHelper.BuildDoPay(tbout_trade_no, IpAddress, amount.ToString());
                log.Write(string.Format("提交支付信息[PostPayInfo]:{0}", JsonHelper.ObjectToJSON(postData)), true);

                string resData = Utils.HttpSubmit(ybgHelper.Req_Url, postData);
                log.Write(string.Format("预支付返回信息[Utils.HttpSubmit]:{0}", JsonHelper.ObjectToJSON(resData)), true);
                YFTPayResult PayInfo = ybgHelper.GetPrePayInfo(resData);

                if (PayInfo.return_code == "0")
                {
                    string payLink = PayInfo.pay_params.pay_info.Replace("\n", "");
                    string ticket = new Uri(payLink).Query;
                    UsersPayDetailEntity entity = new UsersPayDetailEntity()
                    {
                        RechargeNo = "0",
                        Amount = amount,
                        CreateTime = DateTime.Now,
                        FormalitiesFees = 0,
                        OrderNo = tbout_trade_no,
                        PayType = "YFB_Pay",
                        Result = 0,
                        UserID = userid,
                        OutRechargeNo = "0"
                    };

                    long entityResult = new UsersPayDetailBLL().InsertEntity(entity);
                    if (entityResult > 0)
                    {
                        //支付成功
                        result = new PreparePaymentResult()
                        {
                            Code = (int)ResultCode.Success,
                            Msg = Common.GetDescription(ResultCode.Success),
                            Data = new PreparePaymentEnttiy_WFT()
                            {
                                TokenID = ticket,
                                OrderNo = tbout_trade_no,
                                PayLink = payLink
                            }
                        };
                    }
                    else
                    {
                        //支付失败
                        result = new PreparePaymentResult()
                        {
                            Code = (int)ResultCode.PayDetailsFailure,
                            Msg = Common.GetDescription(ResultCode.PayDetailsFailure)
                        };
                    }
                }
                else
                    result = new PreparePaymentResult()
                    {
                        Code = (int)ResultCode.PayDetailsFailure,
                        Msg = Common.GetDescription(ResultCode.PayDetailsFailure)
                    };
            }
            catch (Exception ex)
            {
                result = new PreparePaymentResult()
                {
                    Code = (int)ResultCode.Error,
                    Msg = ex.Message
                };
                log.Write(string.Format("提交支付信息错误[PostPayInfo](userid:{0};amount:{1};IpAddress:{2};tbbody:{3};tbattach:{4}): {5}", userid, amount, IpAddress, tbbody, tbattach, ex.Message), true);
            }
            return result;
        }
       
        /// <summary>
        /// 验证订单号是否已存在数据库
        /// </summary>
        /// <returns></returns>
        private string GetNotbout_trade_no()
        {
            string tbout_trade_no = WFTPayHelper.Nmrandom();
            bool result = new UsersPayDetailBLL().IsTboutTradeNo(tbout_trade_no);
            if (result)
                return tbout_trade_no;
            else
                return GetNotbout_trade_no();
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>  
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }       

        #region 自定义方法
        /// <summary>
        /// 银付宝预支付
        /// 接口调用
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="Amount"></param>
        /// <param name="IpAddress"></param>
        /// <param name="tbBody"></param>
        /// <param name="tbAttach"></param>
        /// <returns></returns>
        public PreparePaymentResult YFBH5Prepayment(long UserCode, long Amount, string tbBody, string tbAttach)
        {
            PreparePaymentResult result = null;
            try
            {
                if (Amount <= 0) //验证充值金额
                    result = new PreparePaymentResult()
                    {
                        Code = (int)ResultCode.PayAmountError,
                        Msg = Common.GetDescription(ResultCode.PayAmountError)
                    };
                else
                    result = this.PostPayInfo(UserCode, Amount, Utils.RequestIP, tbBody, tbAttach);
            }
            catch (Exception ex)
            {
                log.Write("银付宝预支付异常：" + Utils.ReplaceStr(ex.Message) + "\r\n" + ex.StackTrace, true);
                result = new PreparePaymentResult()
                {
                    Code = (int)ResultCode.InterfaceException,
                    Msg = string.Format("{0}{1}", Common.GetDescription(ResultCode.InterfaceException), Utils.ReplaceStr(ex.Message))
                };
            }
            return result;
        }       
        #endregion
    }
}